<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/main.php';

/**
 * Контроллер главной страницы сайта
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Front extends Main {
   
   /**
    * Массив использованых видео
    *
    * @var array
    */
   var $_excluded = array();
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return Front
    */
   function Front() {
      parent::Main();
      // Подгружаем хелперы
      $this->load->helper('content');
      $this->load->helper('thumbnail');
      // Устанавливаем лайаут
      $this->set_layout('front');
   } // end Front
   
   /**
    * Точка входа
    *
    */
   function index() {
      $data = array(
         'popular' => $this->_get_popular_results(),
         'novelty' => $this->_get_novelty_results(),
         'latest'  => $this->_get_latest_results(),
         'rating'  => $this->_get_rating_results(),
         'random'  => $this->_get_random_results()
      );
      $data['no_popular'] = empty($data['popular']) ? array(array()) : array();
      $data['no_novelty'] = empty($data['novelty']) ? array(array()) : array();
      $data['no_latest'] = empty($data['latest']) ? array(array()) : array();
      $data['no_rating'] = empty($data['rating']) ? array(array()) : array();
      $data['no_random'] = empty($data['random']) ? array(array()) : array();
      
      $content = $this->parser->parse('front/body.html', $data, true);
      $this->set_content($content);
      $this->display();
   }
   
   /**
    * Получение новых поступлений
    *
    * @return array
    */
   function _get_latest_results() {
      // Строим запрос
      $this->db->select('v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
         ->select('v.num_downloaded, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
         ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
         ->from('videos v')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->where('v.year <=', date('Y'))
         ->group_by('v.id_video')
         ->order_by('v.date_created', 'desc')
         ->limit($this->variables->get('catalog_num_cols'));
      if (!empty($this->_excluded)) {
         $this->db->where_not_in('v.id_video', $this->_excluded);
      }
      $query = $this->db->get();
      return $this->_get_results($query);
   }
   
   /**
    * Получение новинок кино
    *
    * @return array
    */
   function _get_novelty_results() {
      // Получаем пограничный год
      $year = date('Y') - 1;
      // Строим запрос
      $this->db->select('v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
         ->select('v.num_downloaded, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
         ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
         ->from('videos v')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->where('v.year >=', $year)
         ->group_by('v.id_video')
         ->order_by('v.year', 'desc')
         ->order_by('v.date_created', 'desc')
         ->limit($this->variables->get('catalog_num_cols'));
      if (!empty($this->_excluded)) {
         $this->db->where_not_in('v.id_video', $this->_excluded);
      }
      $query = $this->db->get();
      return $this->_get_results($query);
   }
   
   /**
    * Получение новых поступлений
    *
    * @return array
    */
   function _get_random_results() {
      // Строим запрос
      $this->db->select('v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
         ->select('v.num_downloaded, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
         ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
         ->from('videos v')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->where('v.year <=', date('Y'))
         ->group_by('v.id_video')
         ->order_by('v.id_video', 'random')
         ->limit($this->variables->get('catalog_num_cols'));
      if (!empty($this->_excluded)) {
         $this->db->where_not_in('v.id_video', $this->_excluded);
      }
      $query = $this->db->get();
      return $this->_get_results($query);
   }
   
   /**
    * Получение популярного видео
    *
    * @return array
    */
   function _get_popular_results() {
      // Строим запрос
      $this->db->select('v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
         ->select('v.num_downloaded, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
         ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
         ->from('videos v')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->where('v.year <=', date('Y'))
         ->group_by('v.id_video')
         ->order_by('v.num_downloaded', 'desc')
         ->order_by('v.date_created', 'desc')
         ->limit($this->variables->get('catalog_num_cols'));
      if (!empty($this->_excluded)) {
         $this->db->where_not_in('v.id_video', $this->_excluded);
      }
      $query = $this->db->get();
      return $this->_get_results($query);
   }
   
   /**
    * Получение рейтингового видео
    *
    * @return array
    */
   function _get_rating_results() {
      // Строим запрос
      $this->db->select('v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
         ->select('v.num_downloaded, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
         ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
         ->from('videos v')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->where('v.year <=', date('Y'))
         ->group_by('v.id_video')
         ->order_by('rating', 'desc')
         ->order_by('v.num_ratings', 'desc')
         ->order_by('v.date_created', 'desc')
         ->limit($this->variables->get('catalog_num_cols'));
      if (!empty($this->_excluded)) {
         $this->db->where_not_in('v.id_video', $this->_excluded);
      }
      $query = $this->db->get();
      return $this->_get_results($query);
   }
   
   /**
    * Получение результатов
    *
    * @param $query
    * @return array
    */
   function _get_results($query) {
      $results = array();
      if (0 < $query->num_rows()) {
         foreach ($query->result_array() as $row) {
            if (!in_array($row['id_video'], $this->_excluded)) {
               array_push($this->_excluded, $row['id_video']);
            }
            if (empty($row['image'])) {
               $row['image'] = base_url() . 'images/no_image.jpg';
            } else {
               $row['image'] = base_url() . create_thumbnail($row['image'], 100, 150);
            }
            $row['uid'] = md5(uniqid());
            $row['description'] = get_abstract(stripslashes($row['description']), 200);
            array_push($results, $row);
         }
      }
      return $results;
   }
   
   /**
    * Метод построения title страницы
    *
    * @return string
    */
   function _build_title() {
      $title = str_replace(array('{%page_title%}'), array($this->_title), $this->lang->line('main_title_template'));
      return $title;
   }
   
}
